import { updateResume, getResume, validateResumeContent } from "~/server/database/services/resumeService";
import authMiddleware from "~/server/middleware/auth";

export default defineEventHandler(async (event) => {
  try {
    // 使用认证中间件获取用户信息
    await authMiddleware(event);
    
    const id = getRouterParam(event, "id");
    const body = await readBody(event);
    const { title, content } = body;
    
    // 从event.context中获取用户信息
    const user = event.context.user;

    if (!id) {
      throw createError({
        statusCode: 400,
        statusMessage: "简历ID是必需的"
      });
    }

    // 验证输入数据
    if (title !== undefined && (typeof title !== 'string' || title.trim().length === 0)) {
      throw createError({
        statusCode: 400,
        statusMessage: "标题不能为空"
      });
    }

    if (content !== undefined) {
      if (typeof content !== 'string' || content.trim().length === 0) {
        throw createError({
          statusCode: 400,
          statusMessage: "内容不能为空"
        });
      }
      
      // 验证JSON格式
      if (!validateResumeContent(content)) {
        throw createError({
          statusCode: 400,
          statusMessage: "内容必须是有效的JSON格式"
        });
      }
    }

    if (!title && !content) {
      throw createError({
        statusCode: 400,
        statusMessage: "至少需要提供标题或内容进行更新"
      });
    }

    // 检查简历是否存在
    const existingResume = await getResume(parseInt(id));
    if (!existingResume) {
      throw createError({
        statusCode: 404,
        statusMessage: "简历不存在"
      });
    }
    
    // 检查简历是否属于当前用户
    if (existingResume.dataValues.userId !== user.id) {
      throw createError({
        statusCode: 403,
        statusMessage: "无权修改此简历"
      });
    }

    const updateData: { title?: string; content?: string } = {};
    if (title) updateData.title = title;
    if (content) updateData.content = content;

    const result = await updateResume(parseInt(id), updateData);
    
    return {
      success: true,
      data: result,
      message: "简历更新成功"
    };
  } catch (error: any) {
    console.error("更新简历失败:", error);
    if (error.statusCode) {
      throw error;
    }
    throw createError({
      statusCode: 500,
      statusMessage: "更新简历失败"
    });
  }
});
